package xyz.mumuwei.youthcourseserver.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import lombok.extern.slf4j.Slf4j;
import xyz.mumuwei.youthcourseserver.config.AlipayConfig;
import xyz.mumuwei.youthcourseserver.pojo.Order;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mumuwei
 */
@Slf4j
public class AlipayUtil {

    /**
     * 创建请求支付宝沙箱支付
     *
     * @param order 订单信息
     * @return 支付宝支付响应
     * @throws AlipayApiException 支付宝api异常
     */
    public static AlipayTradePagePayResponse createAliPay(Order order) throws AlipayApiException {
        // 创建请求
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.URL,
                AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE);

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(AlipayConfig.NOTIFY_URL);
        request.setReturnUrl(AlipayConfig.PC_RETURN_URL);

        // 构建订单信息
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", order.getCode());
        bizContent.put("total_amount", order.getTotalPrice());
        bizContent.put("subject", order.getCourseName());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        log.info("创建订单，订单信息：{}", order);
        log.info(String.valueOf(bizContent));

        // 发送请求
        request.setBizContent(bizContent.toString());
        return alipayClient.pageExecute(request);
    }

    /**
     * 根据订单编号查询支付宝订单状态
     *
     * @param code 订单编号
     * @return 支付宝查询相应
     * @throws AlipayApiException 支付宝请求异常
     */
    public static AlipayTradeQueryResponse queryOrderStatus(String code) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.URL,
                AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE);

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", code);
        request.setBizContent(bizContent.toString());
        return alipayClient.execute(request);
    }

    /**
     * 验签
     */
    public static Boolean signVerified(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params = new HashMap<>(40);
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        // 商户订单号
        // String out_trade_no = request.getParameter("out_trade_no");
        //调用SDK验证签名
        return AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);
    }

    /**
     * 创建支付宝沙箱支付，手机网站支付
     *
     * @param order 订单信息
     * @return 支付相应参数
     * @throws AlipayApiException 支付宝异常
     */
    public static AlipayTradeWapPayResponse createWapAlipay(Order order) throws AlipayApiException {
        // 创建请求
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.URL,
                AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(AlipayConfig.NOTIFY_URL);
        request.setReturnUrl(AlipayConfig.WAP_RETURN_URL);

        // 构建订单信息
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", order.getCode());
        bizContent.put("total_amount", order.getTotalPrice());
        bizContent.put("subject", order.getCourseName());
        bizContent.put("product_code", "QUICK_WAP_WAY");

        // 发送请求
        request.setBizContent(bizContent.toString());
        return alipayClient.pageExecute(request);
    }

}